const cache = require("../cache")
const sendWechatNotify = require('./wechatNotify')
const btsHelper = require('../btsHelper')
const btcAssetId = "1.3.1570"
const orderAmountLmit = 30000 //大于3000的订单才通知

const monitorCoins = {
    "XSD": "1.3.4381",
    "TRTT": "1.3.3902"
}
const asssetList = Array.from(Object.keys(monitorCoins), (val, index) => monitorCoins[val]);

var recentlyTransfer = []
var recentlyOrders = []
var lastPrice = {}

var updateLastPrice = 0

async function IsBotOrder(buyAlt, amount, price, sellerId, assetName) {
    var isBOt = recentlyOrders.filter(function (x) {
        return x.buyAlt == buyAlt &&
            x.sellerId == sellerId &&
            Math.abs(x.price - price) < 0.15 &&
            Math.abs(x.amount - amount) < 200
    }).length > 0

    if(lastPrice[assetName] == undefined){
        lastPrice[assetName] = await cache.getLastPrice(assetName)
    }
    
    if (lastPrice[assetName] != undefined &&
        Math.abs(lastPrice[assetName] - price) > 25) {
        return true
    }

    //if(!isBOt)recentlyOrders.push({ "buyAlt": buyAlt, "amount": amount, "price": price, "sellerId": sellerId })
    recentlyOrders.push({
        "buyAlt": buyAlt,
        "amount": amount,
        "price": price,
        "sellerId": sellerId
    })
    if (recentlyOrders.length > 50) {
        recentlyOrders = recentlyOrders.slice(25)
        lastPrice[assetName] = await cache.getLastPrice(assetName)
    }

    return isBOt
}

async function handleOrderCreated(trans) {

    var op = trans.operations[0][0]
    if (op != 1) {
        return
    }

    const txid = btsHelper.getTxId(trans)
    if (recentlyTransfer.includes(txid)) {
        return
    }

    var operation = trans.operations[0][1]

    const seller_id = operation.seller;
    const fill_or_kill = operation.fill_or_kill
    const sell_amount = operation.amount_to_sell.amount
    const sell_assetId = operation.amount_to_sell.asset_id.toString()
    const received_amount = operation.min_to_receive.amount
    const received_assetId = operation.min_to_receive.asset_id.toString()

    const includeSell = asssetList.includes(sell_assetId)
    const includeRecv = asssetList.includes(received_assetId)
    if (!(includeSell || includeRecv)) {
        return
    }

    var price = ""
    var amount = 0

    var buyAlt = false;
    if (btcAssetId == sell_assetId) {
        //卖出BTC,获取AltCoin
        const asset = await cache.getAssetSymbol(received_assetId)
        const precision = asset.precision
        const precisionAmount = Math.pow(10, precision)
        buyAlt = true
        price = sell_amount / (received_amount / precisionAmount) //sat
        amount = received_amount / precisionAmount
    } else if (btcAssetId == received_assetId) {
        //获取BTC,卖出AltCoin
        buyAlt = false
        const asset = await cache.getAssetSymbol(sell_assetId)
        const precision = asset.precision
        const precisionAmount = Math.pow(10, precision)
        price = received_amount / (sell_amount / precisionAmount) //sat
        amount = sell_amount / precisionAmount
    } else {
        //非CB交易
        return
    }

    amount = Math.round(amount)
    price = price.toFixed(3)

    if (amount < orderAmountLmit) {
        console.log("order craeted notify passed, amount limit trigger")
        return
    }

    const received_asset = await cache.getAssetSymbol(received_assetId)
    const received_assetName = received_asset.symbol
    const sell_asset = await cache.getAssetSymbol(sell_assetId)
    const sell_assetName = sell_asset.symbol

    if (await IsBotOrder(buyAlt, amount, price, seller_id, buyAlt ? received_assetName : sell_assetName)) {
        console.log("Bot order, PASS")
        return
    }

    var seller = await cache.getAccountName(seller_id)

    var messageTitle = ""
    var messageContent = ""
    if (buyAlt) {
        messageTitle = "BUY_Order_{0}".format(received_assetName)
        messageContent = "{0} 挂出买单 {1} 个 {2} @ {3} sat".format(seller, amount, received_assetName, price)
    } else {
        messageTitle = "SELL_Order_{0}".format(sell_assetName)
        messageContent = "{0} 挂出卖单 {1} 个 {2} @ {3} sat".format(seller, amount, sell_assetName, price)
    }

    if (recentlyTransfer.length > 100) {
        recentlyTransfer = recentlyTransfer.slice(90)
    }

    sendWechatNotify(messageTitle, messageContent)
    console.log(messageContent)
}

module.exports = handleOrderCreated
